package lew.bing.exp.net.exa1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by 刘国兵 on 2018/7/30.
 */
public class DiscardServer {

    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) 创建监听线程
        EventLoopGroup workerGroup = new NioEventLoopGroup();// 创建工作线程
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2) 这个是一个帮助类来配置服务的
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3) 使用哪一种channel来接受消息
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4) 添加处理器
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler()); // 我们创建的DiscardServerHandler登场
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)          // (5) 设置一些选项，为channel的
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) 同上，不过是为childChannel

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new DiscardServer(port).run();
    }
}
